#!/usr/bin/python
#encoding=utf-8

from config import *

def generate_snippet(content, arrwords, maxlen=MAX_SNIPPET_LEN):
	#print "content:"+content+str(len(content))
	if not isinstance(content, unicode):
		content = content.decode("UTF-8")
	contenti = content.lower()
	for i in range(len(arrwords)):
		if not isinstance(arrwords[i], unicode):
			arrwords[i] = arrwords[i].decode("UTF-8")
		arrwords[i] = arrwords[i].lower()
	allpos = []
        case_words = set()
	pos_words = {}
	for word in arrwords:
		#print word
		word = word.strip()
		if word == "":
			continue
		pos = contenti.find(word, 0)
		while pos != -1:
			#print pos
			allpos.append(pos)
			pos_words[pos] = word
			case_words.add(content[pos:pos+len(word)])
			pos = contenti.find(word, pos+1)
	if allpos == []:
		return ""
	allpos.sort()
	rst = {}
	for i in range(len(allpos)):
		t = -1
		visited = {}
		visited[ pos_words[ allpos[i] ] ] = 1
		weight = 100
		for j in range(i+1,len(allpos)):
			if allpos[j]-allpos[i] > maxlen:
				break
			t = j
			if visited.has_key( pos_words[allpos[j]] ):
				weight += 1
			else:
				weight += 100
				visited[ pos_words[ allpos[j]]] = 1
		if t != -1:
			while rst.has_key(weight):
				weight -= 1
			rst[weight] = [allpos[i], allpos[t]]
	if len(allpos)==1:
		pos = allpos[0]
		rst[100] = [pos-maxlen/2+1, pos+maxlen/2-1]
	items = rst.keys()
	items.reverse()
	best = rst[items[0]]
	center = (best[0]+best[1])/2
	#print "center:"+str(center)
	if center>=maxlen/2:
		start = center-maxlen/2
	else:
		start = 0
	#print start,start+maxlen,len(content)
	ret = content[start: start+maxlen]

# 	highlight
	for word in case_words:
		ret = ret.replace(word, '<em class="hl">'+word+'</em>');
	return ret

#if __name__ == "__main__":
def test():
	c = u'但这种方法对于包含正负号的数字字符串无效，因此更为准确的为这样更准确一些，适用性也更广。但如果你已经确信没有正负号，使用字符串的isdigit()方法则更为方便。'
	s = [u'为', u'这', u'但']
	print generate_snippet(c, s)
